<template>
  <div class="patient-list-container">
    <div class="header-actions">
      <h1>患者影像列表</h1>
      <el-button type="primary" @click="$router.push('/upload')">上传新影像</el-button>
    </div>
    
    <el-card v-if="loading" shadow="never" class="flat-card">
      <div class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
    </el-card>
    
    <el-card v-else-if="patients.length === 0" shadow="never" class="flat-card">
      <div class="empty-container">
        <i class="el-icon-warning-outline"></i>
        <p>暂无患者影像数据</p>
        <el-button type="primary" @click="$router.push('/upload')">上传影像</el-button>
      </div>
    </el-card>
    
    <el-card v-else shadow="never" class="flat-card">
      <el-table
        :data="patients"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :cell-style="{ padding: '8px 0' }"
        :row-style="{ cursor: 'default' }">
        <el-table-column
          prop="name"
          label="患者姓名"
          min-width="150">
          <template slot-scope="scope">
            <div class="patient-name">
              <i class="el-icon-user"></i>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="患者ID"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          width="80">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.sex === 'M' ? 'primary' : (scope.row.sex === 'F' ? 'success' : 'info')">
              {{ formatSex(scope.row.sex) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="birthDate"
          label="出生日期"
          width="120">
          <template slot-scope="scope">
            {{ formatDate(scope.row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="studiesCount"
          label="检查数量"
          width="100">
          <template slot-scope="scope">
            <span class="study-count">
              <i class="el-icon-folder"></i>
              <span>{{ scope.row.studiesCount }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="最近检查日期"
          width="120">
          <template slot-scope="scope">
            <div class="study-date">
              <i class="el-icon-date"></i>
              <span>{{ formatDate(scope.row.lastStudyDate) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              :disabled="!hasViewableStudies(scope.row)"
              @click="viewPatient(scope.row)">
              查看
            </el-button>
            <el-button
              size="mini"
              type="danger"
              plain
              @click="confirmDeletePatient(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <div>
        <p>您确定要删除患者 <strong>{{ patientToDelete ? patientToDelete.name : '' }}</strong> 的所有影像数据吗？</p>
        <p class="warning-text">此操作不可逆，删除后数据将无法恢复！</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="deletePatient" :loading="deleting">确认删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import orthancService from '@/services/orthanc'

export default {
  name: 'PatientList',
  data() {
    return {
      patients: [],
      loading: true,
      deleteDialogVisible: false,
      patientToDelete: null,
      deleting: false
    }
  },
  async mounted() {
    await this.loadPatients()
  },
  methods: {
    async loadPatients() {
      this.loading = true;
      try {
        const patients = await orthancService.getPatients();
        
        // 检查返回的数据格式
        if (Array.isArray(patients)) {
          // 过滤掉没有研究的患者
          this.patients = patients.filter(patient => 
            patient.studies && patient.studies.length > 0
          );
          
          console.log('加载的患者数据:', this.patients);
          
          // 如果没有有效的患者数据
          if (this.patients.length === 0) {
            console.log('没有找到有效的患者数据');
          }
        } else {
          console.error('患者数据格式不正确:', patients);
          this.$message.error('患者数据格式不正确');
        }
      } catch (error) {
        console.error('加载患者列表失败:', error);
        this.$message.error('加载患者列表失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    
    formatDate(dateString) {
      if (!dateString || dateString === 'Unknown') return '未知'
      
      // 如果是DICOM格式的日期 (YYYYMMDD)
      if (dateString.length === 8) {
        return `${dateString.substring(0, 4)}-${dateString.substring(4, 6)}-${dateString.substring(6, 8)}`
      }
      
      return dateString
    },
    
    formatSex(sex) {
      if (sex === 'M') return '男'
      if (sex === 'F') return '女'
      return '未知'
    },
    
    hasViewableStudies(patient) {
      return patient && 
             patient.studies && 
             Array.isArray(patient.studies) && 
             patient.studies.length > 0 && 
             patient.studies[0].ID;
    },
    
    handleRowClick() {
      // 不执行任何操作
    },
    
    viewPatient(patient) {
      // 检查患者是否有研究
      if (this.hasViewableStudies(patient)) {
        // 获取第一个研究的ID
        const studyId = patient.studies[0].ID;
        
        // 确保我们有一个有效的ID
        if (!studyId) {
          console.error('无效的研究ID:', patient.studies[0]);
          this.$message.error('无法获取有效的研究ID');
          return;
        }
        
        console.log('跳转到查看器，患者ID:', patient.id, '研究ID:', studyId);
        this.$router.push(`/viewer/${patient.id}/${studyId}`);
      } else {
        this.$message.warning('该患者没有可查看的影像');
      }
    },
    
    confirmDeletePatient(patient) {
      this.patientToDelete = patient
      this.deleteDialogVisible = true
    },
    
    async deletePatient() {
      if (!this.patientToDelete) return
      
      this.deleting = true
      try {
        const result = await orthancService.deletePatient(this.patientToDelete.id)
        
        if (result.success) {
          this.$message.success('患者影像数据已成功删除')
          // 重新加载患者列表
          await this.loadPatients()
        } else {
          this.$message.error(`删除失败: ${result.error || '未知错误'}`)
        }
      } catch (error) {
        console.error('删除患者数据失败:', error)
        this.$message.error(`删除失败: ${error.message || '未知错误'}`)
      } finally {
        this.deleting = false
        this.deleteDialogVisible = false
        this.patientToDelete = null
      }
    }
  }
}
</script>

<style scoped>
.patient-list-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  padding: 40px;
  text-align: center;
}

.empty-container i {
  font-size: 48px;
  color: #909399;
  margin-bottom: 20px;
}

.empty-container p {
  margin-bottom: 20px;
  color: #606266;
}

.warning-text {
  color: #E6A23C;
  font-weight: bold;
}

.patient-name, .study-date, .study-count {
  display: flex;
  align-items: center;
}

.patient-name i, .study-date i, .study-count i {
  margin-right: 5px;
  color: #409EFF;
}

.study-count i {
  font-size: 16px;
}

.flat-card {
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05) !important;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .patient-list-container {
    padding: 10px;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-button {
    padding: 6px 10px;
    font-size: 12px;
  }
}
</style> 